package com.reservation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reservation.common.BusinessException;
import com.reservation.entity.Message;
import com.reservation.entity.User;
import com.reservation.mapper.MessageMapper;
import com.reservation.mapper.UserMapper;
import com.reservation.service.MessageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 留言服务实现类
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message addMessage(Message message) {
        // 设置留言时间、创建时间和更新时间
        message.setMessageTime(LocalDateTime.now());
        message.setCreateTime(LocalDateTime.now());
        message.setUpdateTime(LocalDateTime.now());

        // 保存留言信息
        messageMapper.insert(message);

        return message;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message replyMessage(Long id, String reply) {
        // 检查留言是否存在
        Message message = messageMapper.selectById(id);
        if (message == null) {
            throw new BusinessException("留言不存在");
        }

        // 更新回复信息
        Message updateMessage = new Message();
        updateMessage.setId(id);
        updateMessage.setReply(reply);
        updateMessage.setReplyTime(LocalDateTime.now());
        updateMessage.setUpdateTime(LocalDateTime.now());
        messageMapper.updateById(updateMessage);

        // 返回更新后的留言信息
        return messageMapper.selectById(id);
    }

    @Override
    public Message getMessageById(Long id) {
        Message message = messageMapper.selectById(id);
        if (message == null) {
            throw new BusinessException("留言不存在");
        }
        return message;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMessage(Long id) {
        // 检查留言是否存在
        Message message = messageMapper.selectById(id);
        if (message == null) {
            throw new BusinessException("留言不存在");
        }

        // 删除留言
        return messageMapper.deleteById(id) > 0;
    }

    @Override
    public IPage<Message> getMessageList(Page<Message> page, Long userId, String content, Boolean hasReply) {
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        if (userId != null) {
            queryWrapper.eq(Message::getUserId, userId);
        }
        if (StringUtils.isNotBlank(content)) {
            queryWrapper.like(Message::getContent, content);
        }
        if (hasReply != null) {
            if (hasReply) {
                queryWrapper.isNotNull(Message::getReply);
            } else {
                queryWrapper.isNull(Message::getReply);
            }
        }


        // 按留言时间降序排序
        queryWrapper.orderByDesc(Message::getMessageTime);
        Page<Message> messagePage = messageMapper.selectPage(page, queryWrapper);
        List<Message> records = messagePage.getRecords();
        for (Message message : records) {
            User user = userMapper.selectById(message.getUserId());
            message.setUsername(user.getName());
        }
        // 执行查询
        return messagePage;
    }

    @Override
    public List<Message> getUserMessages(Long userId) {
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Message::getUserId, userId);
        queryWrapper.orderByDesc(Message::getMessageTime);
        return messageMapper.selectList(queryWrapper);
    }

    @Override
    public List<Message> getLatestMessages(int limit) {
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Message::getMessageTime);

        // 分页查询，只取前limit条
        Page<Message> page = new Page<>(1, limit);
        IPage<Message> messagePage = messageMapper.selectPage(page, queryWrapper);

        return messagePage.getRecords();
    }
}